﻿using Autofac;
using Autofac.Integration.WebApi;
using SignalRApp.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace SignalRApp
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //------AutoFac DI-------
            var builder = new ContainerBuilder();
            SetupResolveRules(builder);
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());               //RegisterApiControllers方法
            var container = builder.Build();
            HttpConfiguration config = GlobalConfiguration.Configuration;//注意此处HttpConfiguration类的 config对象，一定不要new,要从GlobalConfiguration获取
            config.DependencyResolver = (new AutofacWebApiDependencyResolver(container));      //注意此处与MVC依赖注入不同
            //---------------------------------------------------------

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }


        /// <summary>
        ///  AutoFac
        /// </summary>
        /// <param name="builder"></param>
        private static void SetupResolveRules(ContainerBuilder builder)
        {
            var assembly = Assembly.Load("SignalRApp");   //根据程序集名称加载程序集
            builder.RegisterAssemblyTypes(assembly).SingleInstance();//每次都返回同一个实例
            builder.RegisterGeneric(typeof(Repository<>)).InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();
            //builder.RegisterAssemblyTypes(assembly).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();
        }
    }
}
